
import { useParams } from "react-router-dom";
import { useContext, useEffect, useState } from "react";
import React from "react";
import "./index.css";
import { BookListContext } from "../../App";
import ToolBar from "../../components/ToolBar";
import NoteBox from "../../components/NoteBox";
import NoteReadBox from "../../components/NoteReadBox";
import './index.css';
import ReaderControls from "../../components/readerControls";
// import ReaderSetting from "../../components/readerSetting";
import { Typography, Drawer, Button, Space,Tabs,List } from 'antd';
import {
  MenuOutlined,
  HomeOutlined,
  BookOutlined,
  SettingOutlined
} from '@ant-design/icons';

const { Title, Paragraph, Text, Link } = Typography;
const { TabPane } = Tabs;

//读取文件
function readFile(input) {
  const reader = new FileReader();
  const out = "";
  reader.readAsText(input); //读取文件的内容,也可以读取文件的URL
  reader.onload = function () {
    return this.result;
  };
}

//放置toolBar功能所需变量
let downPageX = 0
let downPageY = 0
let downOffsetX = 0
let downClientY = 0

export default function Index() {
  const params = useParams();
  const bookName = params.bookName;
  const bookListContext = useContext(BookListContext);
  const [bookDetail, setBookDetail] = useState("");
  const [theme, setTheme] = useState('normal');
  const [fontFamily, setFontFamily] = useState('SimHei');
  const [fontSize, setFontSize] = useState(24);
  const [paraStyle, setParaStyle] = useState('well');
  const defaultSetting = {
    theme:  theme ,
    setTheme:  setTheme ,
    fontFamily:  fontFamily ,
    setFontFamily:  setFontFamily ,
    fontSize:  fontSize ,
    setFontSize:  setFontSize ,
    paraStyle:  paraStyle ,
    setParaStyle: setParaStyle,
  }
  useEffect(() => {
    const index = bookListContext.bookListContext.findIndex((value) => {
      return value.bookName === bookName;
    });
    const input=bookListContext.bookListContext[index].file;
    const reader = new FileReader();
    reader.readAsText(input,'gb2312'); //读取文件的内容,也可以读取文件的URL
    reader.onload = function () {
      setBookDetail(this.result);
    };
  },[]);
  // function getBookDetails(bookName) {}
  // const details = getBookDetails(bookName);
  //文本处理
  var bookContext = bookDetail.split(/\r?\n/);
  const catalogue = [];
  const bookmarks = [];


  const [visible, setVisible] = useState(false);
  const [title, setTitle] = useState(false);
  const [dataSource, setDataSource] = useState(false);

  const showDrawer_1 = () => {
    setVisible(true);
    setTitle('目录');
    setDataSource(catalogue);
  };

  const showDrawer_2 = () => {
    setVisible(true);
    setTitle('书签');
    setDataSource(bookmarks);
  };

  const onClose = () => {
    setVisible(false);
  };

  //------------------------------------放置toolBar功能代码start
  let lineHight = 36
  let pageWidth = 878
  let toolBarWidth = 200
  let toolBarHight = 40


  let initialToolBarProps = {
    left:'',
    top:'',
    display:false,
    selectedText:'',
    noteBoxFlag:false,
    noteReadBoxFlag:false,
    noteReadBoxText:'',
    styleBtnFlag:false,
  }

  let [toolBarProps, setToolBarProps] = useState(initialToolBarProps);

  //鼠标按下事件，记录按下位置，并清除toolbar、notebox与notereadbox
  function mouseDownEvent(e){
    downPageX = e.nativeEvent.pageX
    downPageY = e.nativeEvent.pageY
    downOffsetX = e.nativeEvent.offsetX
    downClientY = e.nativeEvent.clientY
    console.log('mouseDownEvent',e);

    if( toolBarProps.display === true){
      toolBarProps.display = false
      noteBox(false)
      let newtoolBarProps = {...toolBarProps}
      setToolBarProps(newtoolBarProps)
    }
    if(toolBarProps.noteReadBoxFlag === true){
      toolBarProps.noteReadBoxFlag = false
      let newtoolBarProps = {...toolBarProps}
      setToolBarProps(newtoolBarProps)
    }
  }

  //鼠标抬起事件，显示toolbar
  function mouseUpEvent(e){
    let {pageX,pageY,offsetX,offsetY} = e.nativeEvent

    //若点击其他地方，则关闭toolbar
    if(downPageX <= pageX && pageX-downPageX<=10){
      toolBarProps.display = false
      toolBarProps.styleBtnFlag = false
      let newtoolBarProps = {...toolBarProps}
      setToolBarProps(newtoolBarProps)
      return
    }

    console.log(window.getSelection().toString())
    toolBarProps.selectedText = window.getSelection().toString()



    toolBarProps.left = offsetX > downOffsetX? (offsetX- (offsetX-downOffsetX)/2 - toolBarWidth/2 + 'px') : (downOffsetX + ( pageWidth - downOffsetX)/2 - toolBarWidth/2 + 'px')

    toolBarProps.top = downClientY > 2*lineHight? (Math.ceil((downPageY-60)/lineHight)*lineHight - toolBarHight - 10 + 'px') : (Math.ceil((downPageY-60)/lineHight)*lineHight + 30 +'px' )


    toolBarProps.display = true

    let newtoolBarProps = {...toolBarProps}
    setToolBarProps(newtoolBarProps)

  }

  //高亮
  function highLine(e){
    let bookDetailSplit = bookDetail.split(toolBarProps.selectedText)
    let newBookDetail = bookDetailSplit.join(`<span class='highLineText'>${toolBarProps.selectedText}</span>`)

    setBookDetail(newBookDetail)
  }
  //划线
  function underLine(e){
    let bookDetailSplit = bookDetail.split(toolBarProps.selectedText)
    let newBookDetail = bookDetailSplit.join(`<span class='underLineText'>${toolBarProps.selectedText}</span>`)
    setBookDetail(newBookDetail)
    console.log('underline');
  }
  //notebox显示
  function noteBox(noteBoxF){
    toolBarProps.noteBoxFlag = noteBoxF
    let newtoolBarProps = {...toolBarProps}
    setToolBarProps(newtoolBarProps)
  }

  //添加Note
  function addNote(selectedText){

    let bookDetailSplit = bookDetail.split(selectedText)
    let newBookDetail = bookDetailSplit.join(`<span class='notedText' >${selectedText}</span>`)
    setBookDetail(newBookDetail)
    console.log('addnote调用完成');
  }
  //读取Note
  function readNote(notedText){

      return (e)=>{
        // e.stopPropagation()
        console.log(notedText);
        toolBarProps.noteReadBoxFlag = true
        toolBarProps.noteReadBoxText = notedText
        let newtoolBarProps = {...toolBarProps}
        setToolBarProps(newtoolBarProps)
      }
  }

  function handleStyleText(selectedText){
    return (e)=>{
      toolBarProps.display = true
      toolBarProps.styleBtnFlag = true
      toolBarProps.selectedText = selectedText

      // toolBarProps.left = offsetX > downOffsetX? (offsetX- (offsetX-downOffsetX)/2 - toolBarWidth/2 + 'px') : (downOffsetX + ( pageWidth - downOffsetX)/2 - toolBarWidth/2 + 'px')

      // toolBarProps.top = downClientY > 2*lineHight? (Math.ceil((downPageY-60)/lineHight)*lineHight - toolBarHight - 10 + 'px') : (Math.ceil((downPageY-60)/lineHight)*lineHight + 30 +'px' )

      toolBarProps.left = downOffsetX - toolBarWidth/2 +'px'

      toolBarProps.top = downClientY > 2*lineHight? (Math.ceil((downPageY-60)/lineHight)*lineHight - toolBarHight - 10 + 'px') : (Math.ceil((downPageY-60)/lineHight)*lineHight + 30 +'px' )


      let newtoolBarProps = {...toolBarProps}
      setToolBarProps(newtoolBarProps)
    }

  }

  function delectStyle(selectedText){
    return (e)=>{
      console.log('delectStyle',selectedText);

      if(bookDetail.indexOf(`<span class='underLineText'>${selectedText}</span>`) != -1){
        let bookDetailSplit = bookDetail.split(`<span class='underLineText'>${selectedText}</span>`)
        let newBookDetail = bookDetailSplit.join(selectedText)
        setBookDetail(newBookDetail)
        console.log('underLineText');
      }
      else{
        console.log('highLineText');
        let bookDetailSplit = bookDetail.split(`<span class='highLineText'>${selectedText}</span>`)
        let newBookDetail = bookDetailSplit.join(selectedText)
        setBookDetail(newBookDetail)
      }
    }
  }

  //模拟componentDidUpdata()勾子，为notedText添加点击事件
  useEffect(()=>{
    let highLineTextArr = document.querySelectorAll('.highLineText')
    // console.log('highLineTextArr',highLineTextArr);
    for(let i=0;i<highLineTextArr.length;i++){
      if(highLineTextArr[i].onclick == null){
        highLineTextArr[i].onclick = handleStyleText(highLineTextArr[i].innerText)
        // console.log('@@@highLineTextArr[i].innerText',highLineTextArr[i].innerText);
      }
    }

    let underLineTextArr = document.querySelectorAll('.underLineText')
    for(let i=0;i<underLineTextArr.length;i++){
      if(underLineTextArr[i].onclick == null){
        underLineTextArr[i].onclick = handleStyleText(underLineTextArr[i].innerText)
      }
    }
    let notedTextArr = document.querySelectorAll('.notedText')
    for(let i=0;i<notedTextArr.length;i++){
      if(notedTextArr[i].onclick == null){
        let notedText = notedTextArr[i].innerText
        notedTextArr[i].onclick = readNote(notedText)
      }
    }

  })

  function deleteNote(selectedText){
    return (e)=>{

      let bookDetailSplit = bookDetail.split(`<span class='notedText' >${selectedText}</span>`)
      let newBookDetail = bookDetailSplit.join(selectedText)
      setBookDetail(newBookDetail)

      toolBarProps.noteReadBoxFlag = false
      let newtoolBarProps = {...toolBarProps}
      setToolBarProps(newtoolBarProps)
      localStorage.removeItem(selectedText)
    }
  }
  //------------------------------------放置toolBar功能代码end


  return (

    <div className={theme+" readerBackground"}>
      <div className='icon'>
      &nbsp;
        {/* <Button icon={<HomeOutlined />} onClick={()=>this.props.history.go(-1)}></Button>&nbsp; */}
        <Button icon={<MenuOutlined />} shape='circle' size='large' onClick={showDrawer_1} value='5461'></Button>&nbsp;
        <Button icon={<BookOutlined />} shape='circle' size='large' onClick={showDrawer_2} id='2'></Button>&nbsp;
        {/* <Button icon={<SettingOutlined />} onClick={showDrawer_2} id='2'></Button> */}
        <Drawer title={title} placement="left" onClose={onClose} visible={visible} >
          <List
            bordered
            dataSource={dataSource}
            renderItem={item => <List.Item>{item}</List.Item>}
          />
        </Drawer>
      </div>
      <div className={theme + ' readerBody book ' + paraStyle} >
        <Typography className={theme + ' ' + fontFamily}  className='bookDetailBox' style={{fontSize:fontSize,lineHeight:'36px'}} onMouseUp={mouseUpEvent} onMouseDown={mouseDownEvent}>
          <Title>{bookName}</Title>
          {bookContext.map((data,index)=>{
            if(data.search(/^(?=.*第)(?=.*章)/)!=-1){
              catalogue.push(data)

              return <Title level={2} key={index}>{data}</Title>
            }
            return (
                <div>
                  <p key={index} dangerouslySetInnerHTML={{__html:data}} className='bookDetail' style={{marginBottom:'36px'}} ></p>

                </div>
            )

          })}

          <ToolBar {...toolBarProps} highLine={highLine} underLine={underLine} noteBox={noteBox} delectStyle={delectStyle}/>

        </Typography>

        <NoteBox {...toolBarProps} noteBox={noteBox} addNote={addNote}/>
        <NoteReadBox  {...toolBarProps} deleteNote={deleteNote}/>

        <div className='progress'>22.1%</div>
      </div>
      <ReaderControls {...defaultSetting} />
    </div>
  );
}
